package com.yndsoft.jc.supplier.order;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yndsoft.jc.R;
import com.yndsoft.jc.model.ReturnMsg;
import com.yndsoft.jc.supplier.adapter.OrderDetailAdapter;
import com.yndsoft.jc.supplier.base.SupplierBaseActivity;
import com.yndsoft.jc.supplier.model.EventModel;
import com.yndsoft.jc.supplier.model.OrderDetailModel;
import com.yndsoft.jc.supplier.modelput.Entry;
import com.yndsoft.jc.supplier.modelput.Sign;
import com.yndsoft.jc.supplier.net.util.ProgressSubscriber;
import com.yndsoft.jc.supplier.utils.Constants;
import com.yndsoft.jc.supplier.utils.ToastUtil;
import com.yndsoft.jc.supplier.widget.imageselector.ImgSelActivity;
import com.yndsoft.jc.supplier.widget.recyclerview.ScrollLinearLayoutManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OrderDetailActivity extends SupplierBaseActivity implements View.OnClickListener {

    private TextView orderDetailTime;
    private TextView orderDetailNumber;
    private RecyclerView orderDetailResultList;
    private String tag;
    private String id;
    private String signStatus = null;
    private OrderDetailAdapter orderDetailAdapter;
    private int clickPosition;
    private String oDetId;
    private String tempImgPath;
    private Map<Integer, Entry> entryMap = new HashMap<>();
    private List<Entry.Imgs> imgsTemp;
    private Entry entryTemp;

    @Override
    public int getContentResId() {
        return R.layout.activity_order_detail;
    }

    public static void start(Context context, String id, String tag) {
        Intent intent = new Intent(context, OrderDetailActivity.class);
        intent.putExtra(Constants.ID, id);
        intent.putExtra(Constants.TAG, tag);
        context.startActivity(intent);
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        ImageButton barBack = findViewById(R.id.bar_back);
        TextView barTitle = findViewById(R.id.bar_title);
        orderDetailTime = findViewById(R.id.order_detail_time);
        orderDetailNumber = findViewById(R.id.order_detail_number);
        orderDetailResultList = findViewById(R.id.order_detail_result_list);
        Button orderDetailEntry = findViewById(R.id.order_detail_entry);
        Button orderDetailNoPass = findViewById(R.id.order_detail_no_pass);
        Button orderDetailPass = findViewById(R.id.order_detail_pass);
        LinearLayout orderDetailSign = findViewById(R.id.order_detail_sign);

        tag = getIntent().getStringExtra(Constants.TAG);
        if (tag != null) {
            if (tag.equals(Constants.ENTRY)) {
//                orderDetailEntry.setVisibility(View.VISIBLE);
                orderDetailSign.setVisibility(View.GONE);

            } else if (tag.equals(Constants.SIGN)) {
                orderDetailEntry.setVisibility(View.GONE);
                orderDetailSign.setVisibility(View.VISIBLE);
            }
        } else {
            orderDetailEntry.setVisibility(View.GONE);
            orderDetailSign.setVisibility(View.GONE);
        }

        barTitle.setText("订单详情");
        barBack.setOnClickListener(this);
        orderDetailEntry.setOnClickListener(this);
        orderDetailNoPass.setOnClickListener(this);
        orderDetailPass.setOnClickListener(this);
    }

    @Override
    public void initData() {
        id = getIntent().getStringExtra(Constants.ID);
        mHttpUtil.supplierOrderDetail(new ProgressSubscriber(mContext) {
            @Override
            public void next(ReturnMsg returnMsg) {
                switch (returnMsg.getCode()) {
                    case 0:
                        break;
                    case 1:
                        String msg = returnMsg.getInfo();
                        if (msg != null) {
                            OrderDetailModel model = new Gson().fromJson(msg, OrderDetailModel.class);
                            orderDetailTime.setText(model.getCreatetime() != null ? model.getCreatetime() : "");
                            orderDetailNumber.setText("订单号: " + model.getId());
                            List<OrderDetailModel.DetsBean> dets = model.getDets();
                            if (dets != null && dets.size() > 0) {
                                orderDetailResultList.setLayoutManager(new ScrollLinearLayoutManager(mContext));
                                orderDetailAdapter = new OrderDetailAdapter(mContext, OrderDetailActivity.this, dets, tag);
                                orderDetailResultList.setAdapter(orderDetailAdapter);
                                orderDetailAdapter.setOnClickPositionListener(new OnClickPositionListener() {
                                    @Override
                                    public void onClickPosition(int position, String id) {
                                        clickPosition = position;
                                        oDetId = id;
                                    }
                                });
                                orderDetailAdapter.setOnDeletePositionListener(new OnDeletePositionListener() {
                                    @Override
                                    public void onDeletePosition(int parentPosition, int childPosition) {
                                        if (entryMap != null && entryMap.size() > 0 && parentPosition < entryMap.size()) {
                                            for (Map.Entry<Integer, Entry> e : entryMap.entrySet()) {
                                                if (e.getKey() == parentPosition) {
                                                    entryTemp = e.getValue();
                                                    if (entryTemp != null) {
                                                        entryMap.remove(parentPosition);
                                                        imgsTemp = entryTemp.getDets();
                                                        if (imgsTemp != null && imgsTemp.size() > 0 && childPosition < imgsTemp.size()) {
                                                            imgsTemp.remove(childPosition);
                                                        }
                                                        entryTemp.setDets(imgsTemp);
                                                        entryMap.put(clickPosition, entryTemp);
                                                        List<String> paths = new ArrayList<>();
                                                        if (imgsTemp != null && imgsTemp.size() > 0) {
                                                            for (int i = 0; i < imgsTemp.size(); i++) {
                                                                Entry.Imgs imgs = imgsTemp.get(i);
                                                                if (imgs != null) {
                                                                    String img = imgs.getImg();
                                                                    if (img != null) {
                                                                        paths.add(img);
                                                                    }
                                                                }
                                                            }
                                                        }
                                                        orderDetailAdapter.setImgPath(paths);
                                                        orderDetailAdapter.notifyItemChanged(clickPosition);
                                                        entryTemp = null;
                                                        imgsTemp = null;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                });
                            }
                        }
                        break;
                }
            }
        }, "order", mSession.getSid(), id);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            switch (requestCode) {
                case Constants.REQUEST_ENTRY_CODE:
                    List<String> pathList = data.getStringArrayListExtra(ImgSelActivity.INTENT_RESULT);
                    if (pathList != null && pathList.size() > 0) {
                        String path = pathList.get(0);
                        if (path != null) {
//                            Base64UploadImg base64UploadImg = new Base64UploadImg();
//                            base64UploadImg.uploadImg(mContext, path);
//                            base64UploadImg.setOnUpImgListener(new Base64UploadImg.OnUpImgListener() {
//                                @Override
//                                public void onUpImg(String imgBase64) {
//                                    tempImgPath = imgBase64;
//                                }
//                            });
                            if (orderDetailAdapter != null) {
                                if (entryMap.containsKey(clickPosition)) {
                                    for (Map.Entry<Integer, Entry> e : entryMap.entrySet()) {
                                        int key = e.getKey();
                                        if (key == clickPosition) {
                                            entryTemp = e.getValue();
                                        }
                                    }
                                    if (entryTemp != null) {
                                        entryMap.remove(clickPosition);
                                        imgsTemp = entryTemp.getDets();
                                        Entry.Imgs imgs = entryTemp.getImgs();
                                        imgs.setImg(pathList.get(0));
                                        if (imgsTemp == null) {
                                            imgsTemp = new ArrayList<>();
                                        }
                                        imgsTemp.add(imgs);
                                        entryTemp.setDets(imgsTemp);
                                        entryMap.put(clickPosition, entryTemp);
                                    }
                                } else {
                                    entryTemp = new Entry();
                                    entryTemp.setOid(id);
                                    entryTemp.setOdetid(oDetId);
                                    entryTemp.setSid(mSession.getSid());
                                    entryTemp.setCreateadmin(mSession.getId());
                                    entryTemp.setNote("");
                                    Entry.Imgs imgs = entryTemp.getImgs();
                                    imgs.setImg(pathList.get(0));
                                    imgsTemp = new ArrayList<>();
                                    imgsTemp.add(imgs);
                                    entryTemp.setDets(imgsTemp);
                                    entryMap.put(clickPosition, entryTemp);
                                }
                                List<String> paths = new ArrayList<>();
                                if (imgsTemp != null && imgsTemp.size() > 0) {
                                    for (int i = 0; i < imgsTemp.size(); i++) {
                                        Entry.Imgs imgs = imgsTemp.get(i);
                                        if (imgs != null) {
                                            String img = imgs.getImg();
                                            if (img != null) {
                                                paths.add(img);
                                            }
                                        }
                                    }
                                }
                                orderDetailAdapter.setImgPath(paths);
                                orderDetailAdapter.notifyItemChanged(clickPosition);
                                entryTemp = null;
                                imgsTemp = null;
                            }
                        }
                    }
                    break;
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bar_back:
                finish();
                break;
            case R.id.order_detail_entry:
                if (entryMap != null && entryMap.size() > 0) {
                    List<Entry> entryList = new ArrayList<>();
                    for (Map.Entry<Integer, Entry> e : entryMap.entrySet()) {
                        Entry entry = e.getValue();
                        if (entry != null) {
                            entryList.add(entry);
                        }
                    }
                    String json = new Gson().toJson(entryList, new TypeToken<List<Entry>>() {}.getType());
//                    putResult("entry", json);
                } else {
                    showHint("请录入结果！");
                }
                break;
            case R.id.order_detail_no_pass:
                signStatus = "0";
                SignBox.start(mContext);
                break;
            case R.id.order_detail_pass:
                signStatus = "1";
                SignBox.start(mContext);
                break;
        }
    }

    private void putResult(String type, String json) {
        mHttpUtil.entrySignOrder(new ProgressSubscriber(mContext) {
            @Override
            public void next(ReturnMsg returnMsg) {
                if (1 == returnMsg.getCode()) {
                    EventModel model = new EventModel();
                    model.setInteger(Constants.ENTRY_SIGN_ORDER);
                    EventBus.getDefault().post(model);
                    ToastUtil.show(mContext, "操作成功！");
                    finish();
                } else {
                    ToastUtil.show(mContext, "操作失败！");
                }
            }
        }, type, id, mSession.getSid(), json);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 100)
    public void onEvent(EventModel model) {
        if (model != null) {
            int position = model.getInteger();
            String result = model.getString();
            if (-1 == position) {
                Sign sign = new Sign();
                sign.setSid(mSession.getSid());
                sign.setOid(id);
                sign.setPass(signStatus);
                sign.setNote(result);
                putResult("sign", new Gson().toJson(sign));
            } else {
                if (orderDetailAdapter != null) {
                    if (entryMap.containsKey(position)) {
                        for (Map.Entry<Integer, Entry> e : entryMap.entrySet()) {
                            int key = e.getKey();
                            if (key == position) {
                                entryTemp = e.getValue();
                            }
                        }
                        if (entryTemp != null) {
                            entryMap.remove(position);
                            entryTemp.setNote(result);
                            entryMap.put(position, entryTemp);
                        }
                    } else {
                        entryTemp = new Entry();
                        entryTemp.setOid(id);
                        entryTemp.setOdetid(model.getId());
                        entryTemp.setSid(mSession.getSid());
                        entryTemp.setCreateadmin(mSession.getId());
                        entryTemp.setNote(result);
                        imgsTemp = new ArrayList<>();
                        entryTemp.setDets(imgsTemp);
                        entryMap.put(position, entryTemp);
                    }
                    orderDetailAdapter.setResult(result, position);
                    entryTemp = null;
                }
            }

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (null != signStatus) {
            onEvent(new EventModel());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}